﻿
function getUsageData(returnFunction, errorfunction) {
    debug('getUsageData');

    var usernameSetting = System.Gadget.Settings.read("username");
    var passwordSetting = System.Gadget.Settings.read("password"); ;
    
    if (usernameSetting == "" || passwordSetting == "") {
        errorfunction("please configure.");
        return;
    }

    var oReq = getXMLHttpRequest();
    if (oReq != null) {
        oReq.open("GET", "https://clientzone.afrihost.com", true);
        oReq.setRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
        oReq.onreadystatechange = function () {
            if (oReq.readyState == 4 && oReq.status == 200) {
                oReq.open("POST", "https://clientzone.afrihost.com/login", true);
                oReq.setRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
                oReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                oReq.onreadystatechange = function () {
                    if (oReq.readyState == 4 && oReq.status == 200) {
                        var responseText = oReq.responseText;
                        if (responseText.indexOf("clientzone login", 0) > 0) {
                            errorfunction("invalid username or password");
                            return;
                        }

                        var code = $(responseText);
                        var spacerows = code.find("tr.spacerows");
                        var results = new Array();
                        if (spacerows.length > 0) {
                            
                            spacerows.each(function (idx, row) {
                                results[idx] = new Object();
                                var cols = $(row).find('td');
                                var nameText = $.trim($(cols[0]).text());
                                if (nameText.substr(0, 8) != 'Uncapped') {
                                    var gbIdx = nameText.indexOf('GB');
                                    var size = $.trim(nameText.substr(0, gbIdx));
                                    var name = $.trim(nameText.substr(gbIdx + 2));
                                    results[idx].isUncapped = false;
                                    results[idx].name = name;
                                    results[idx].size = parseFloat(size);
                                    results[idx].usedPercentage = parseFloat($.trim($(cols[2]).text().toString()));
                                } else {
                                    results[idx].isUncapped = true;
                                    results[idx].name = nameText;
                                    results[idx].usage = $(cols[1]).text().toString();
                                }


                            });

                            returnFunction(results);
                        }
                        else {
                            // IS Account? 
                            getIsAccountResults(code, oReq, returnFunction);
                        }
                    }
                };
                oReq.send("username=" + usernameSetting + "&password=" + passwordSetting + "&requestedURL=https://clientzone.afrihost.com/");
            }
        };
        oReq.send();
    }
}

function getIsAccountResults(code, oReq, returnFunction) {
    var connectivityAccount = code.find("div.connectivity_account");
    var con_details = connectivityAccount.children('div.con_details');
    var nameText = $.trim(con_details.text());
    var account = nameText.substring(0, nameText.indexOf(' '));
    nameText = $.trim(nameText.substring(nameText.indexOf("-") + 1));
    var accountSearch = 'input[value="' + account + '"]';
    var action = code.find(accountSearch).parent().attr("action");
    var password = code.find('input[name="password"]').val();

    oReq.open("POST", action, true);
    oReq.setRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
    oReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    oReq.onreadystatechange = function () {
        if (oReq.readyState == 4 && oReq.status == 200) {
            var responseText = oReq.responseText.toString();
            var boxIdx = responseText.indexOf("<div id=\"box\" class=\"box\">");
            var endBoxIdx = responseText.indexOf("</div>", boxIdx);
            var box = responseText.substring(boxIdx, endBoxIdx);
            var jBox = $(box);
            var blacks = jBox.find('td.black');
            var usage = "";
            blacks.each(function (idx, row) {
                var siblings = $(row).siblings('td');
                if ($(siblings[0]).text() == "Total MB Used This Month") {
                    usage = $(row).text();
                }
            });

            var results = new Array();
            results[0] = new Object();
            results[0].isUncapped = true;
            results[0].name = nameText;
            results[0].usage = usage;
            
            returnFunction(results);
        }
    };

    oReq.send("username=" + account + "&password=" + password);
}

function debug(message) {
    //console.log(message);
    System.Debug.outputString(message);
}

function debugObj(obj) {
    var output = '';
    for (var property in obj) {
        output += property + ': ' + obj[property] + '; ';
    }
    debug(output);
}


function getXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}